using System.Net.WebSockets;
using System.Text.Json;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.ResponseCompression;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//配置服务（如数据库上下文、自定义服务等）,使它们可用于整个应用程序的依赖项注入。
//builder.Services.AddScoped<MyService>();

//内容协商允许 API 根据请求中的标头提供不同格式的响应，从而支持 JSON、XML 等格式。
//builder.Services.AddControllers().AddXmlDataContractSerializerFormatters();

//通过配置 JSON 序列化程序设置，自定义 JSON 响应格式，例如 camelCase 命名或忽略 null 值。
builder.Services.AddControllers()  
    .AddJsonOptions(options =>  
    {  
        options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;  
        options.JsonSerializerOptions.IgnoreNullValues = true;  
    });

//跨域资源共享 （CORS） 允许从托管在不同域上的 Web 应用程序调用 API。根据您的要求配置 CORS 策略。
builder.Services.AddCors(options =>  
{  
    options.AddPolicy("AllowSpecificOrigin",  
        cpb => cpb.WithOrigins("http://example.com"));  
});  

//健康检测
//builder.Services.AddHealthChecks();  
//app.MapHealthChecks("/health");

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

//中间件 中间件组件形成一个处理请求和响应的管道。可以为日志记录或错误处理等跨领域问题创建自定义中间件
app.Use(async (context, next) =>  
{  
    // Custom logic before passing to the next middleware
    //logger.LogError("This is an error message before the next middleware"); 
    await next();  
    // Custom logic after executing the next middleware  
});

//全局处理异常,允许对未处理的异常进行集中式错误处理、日志记录和标准化的 API 响应
app.UseExceptionHandler(a => a.Run(async context =>  
{  
    var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();  
    var exception = exceptionHandlerPathFeature.Error;  
    // Log the exception, generate a custom response, etc.  
    context.Response.StatusCode = 500;  
    await context.Response.WriteAsJsonAsync(new { Error = "An unexpected error occurred" });  
}));

app.UseCors("AllowSpecificOrigin");

//app.MapHub<ChatHub>("/chathub");

//WebSocket 通过单个长期连接提供全双工通信通道，是实时应用程序的理想选择。
app.UseWebSockets();  
app.Use(async (context, next) =>  
{  
    if (context.WebSockets.IsWebSocketRequest)  
    {  
        WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();  
        // Handle the WebSocket request here  
    }  
    else  
    {  
        await next();  
    }  
});



app.UseResponseCompression();

app.UseAuthorization();

app.MapControllers();

app.Run();
